package com.example.admin.config.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.admin.common.contants.SystemConts;
import com.example.admin.common.exception.BusinessException;
import com.example.admin.common.util.JwtUtil;
import com.example.admin.common.util.UserContext;
import com.example.admin.entity.SysUser;
import com.example.admin.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private SysUserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 放行OPTIONS请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 打印所有请求头
//        java.util.Enumeration<String> headerNames = request.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            log.info("Header: {} = {}", headerName, request.getHeader(headerName));
//        }

        // 放行登录、注册和验证码接口
        String uri = request.getRequestURI();
        if (uri.equals("/api/auth/login") || 
            uri.equals("/api/auth/register") || 
            uri.equals("/api/nav/home") ||
            uri.equals("/api/captcha/get")) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader(SystemConts.AUTH_KEY);
//        log.info("Authorization token: {}", token); // 添加token日志

        if (token == null || token.isEmpty()) {
            throw new BusinessException("未登录或登录已过期");
        }

        try {
            // 验证token
            if (!jwtUtil.validateToken(token)) {
                throw new BusinessException("登录已过期");
            }
            
            // 获取用户信息
            String username = jwtUtil.getUsernameFromToken(token);
            SysUser user = userMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getUsername, username)
            );
            
            if (user == null) {
                throw new BusinessException("用户不存在");
            }
            
            // 将用户信息存入上下文
            UserContext.setUser(user);
            return true;
        } catch (Exception e) {
            log.error("Token验证失败", e); // 添加异常日志
            throw new BusinessException("token验证失败");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理用户上下文
        UserContext.removeUser();
    }
} 